<template>
  <!-- 导航栏 -->
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      z-index="1000"
      @click-left="back"
    />

  <van-checkbox-group v-model="checkedResult" @change="checkedResultChange">
    <div class="cart" v-for="cart in cartList" :key="cart.id">
      <van-checkbox :name="cart.id"></van-checkbox>
      <!-- 滑动单元格 -->
      <van-swipe-cell>
        <van-card
          :num="cart.nums"
          :tag="cart.product.flag_text"
          :price="cart.total"
          :title="cart.product.name"
          :thumb="cart.product.thumbs_text"
          @click="ProductInfo(cart.proid)"
        >
          <template #tags>
            <van-tag plain type="primary" v-for="(prop,key) in cart.prop_list" :key="key">{{prop}}</van-tag>
          </template>
          <template #num>
            <van-stepper 
              v-model="cart.nums"
              :min="1" 
              :max="cart.product.stock"
              @change="onChangeNum" 
              :name="{id:cart.proid,cartid:cart.id}" 
              @click.stop/>
          </template>
        </van-card>


        <!-- 滑动单元格插槽 右侧滑动 -->
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="onDelCart(cart.id)"
            @click.stop
          />
        </template>

      </van-swipe-cell>
    </div>
  </van-checkbox-group>

  <!-- 提交动作栏 -->
  <van-submit-bar :price="price" button-text="提交订单" @submit="onSubmit">
    <van-checkbox 
      v-model="isCheckAll"
      :indeterminate="isIndeterminate"
      @change="checkAllChange"
    >
    全选
    </van-checkbox>
  </van-submit-bar>
</template>

<script setup>
import { watch } from "vue"

  const {proxy} = getCurrentInstance()

  const ProductInfo = (id) => proxy.$router.push({path:'/product/info',query:{id}})

  //返回上一页
  const back = () => proxy.$router.push('/')
  const cartList = ref([])
  const price = ref(0)
  const checkList = ref([])
  const getCartList = async()=>{
    let result = await proxy.$GET({
      url:'/product/cart',
    })
    cartList.value = result
    price.value = result.reduce((pre,cur)=>{
      if(cur.status=='1'){
        return pre+parseFloat(cur.total)*100
      }
      return pre
    },0)
    return result
  }
  const isInit = ref(true)
  onBeforeMount(async()=>{
    let result = await getCartList()
    checkList.value = result.map(v=>v.id)
    checkedResult.value = result.filter(v=>v.status=='1').map(v=>v.id)
  })
  
  const onChangeNum = async(value,detail)=>{
    if(!value||value<=0){
      value = 1
    }
    let result = await proxy.$PUT({
      url:'/product/cart',
      params:detail.name,
      data:{nums:value}
    })
    if(!result.code){
      showFailToast({
        message: result.msg,
        duration: 1000,
      })
    }else{
      getCartList()
    }
  }
  const onDelCart = async(cartid)=>{
    let result = await proxy.$DEL({
      url:'/product/cart',
      params:{cartid}
    })
    if(!result.code){
      showFailToast({
        message: result.msg,
        duration: 1000,
      })
    }else{
      let result = await getCartList()
      checkList.value = result.map(v=>v.id)
    }
  }
  const isCheckAll = ref(false);
  const checkedResult = ref([]);
  const isIndeterminate = ref(true);
  const checkAllChange = (val) => {
    checkedResult.value = val ? checkList.value : []
    isIndeterminate.value = false
  }
  
  const checkedResultChange = async(value) => {
    const checkedCount = value.length
    isCheckAll.value = checkedCount === checkList.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < checkList.value.length
    if(isInit.value){
      isInit.value = false
      return
    }
    let result = await proxy.$PUT({
      url:'/product/cart',
      data:{value}
    })
    if(!result.code){
      showFailToast({
        message: result.msg,
        duration: 1000,
      })
    }
    getCartList()
  }
  const onSubmit = ()=>{
    if(checkedResult.value.length==0){
      showFailToast({
        message: '购买商品不能为空',
        duration: 1000,
      })
      return
    }
    proxy.$router.push('/cart/confirm')
  }
</script>

<style scoped>
  @import url('/assets/css/cart.css');
  /* 添加这段样式后，Primary Button 会变成红色 */
  .cart{
    justify-content:space-evenly;
  }
  .van-swipe-cell{
    width: 90%;
  }
</style>